<?php
/************************FoxPHP威客系统************************/
/*                                                            */
/*  FoxPHP.Com (C)2006-2016 FoxPHP Inc.                       */
/*  This is NOT a freeware, use is subject to license terms   */
/*  FoxPHP威客系统是商业软件,使用于商业用途请购买授权         */
/*  V3.0 2016.3                                               */
/*  foxphp@aliyun.com                                         */
/*  http://www.foxphp.com                                     */
/*                                                            */
/**************************************************************/


namespace Member\Model;
use Think\Model;
use \Org\Util\String;
    
class MemberDialogModel extends MemberModel {

	//protected $insertFields = array('username','usertype','typename','password','powercode','usergroup','groupname','email','unionid','uniontime','regip','dateline','mobile');
	
	//protected $updateFields = array('avatar','SecurityForm');
	
	//字段过滤-----------------------------------------------------------------------------------------------
	//protected $insertFields = array('title','status','rules','icon','color','allowdomainname','allowlogin','allowskillnumber','allowsendsms','feetype','taskfee','SecurityForm');
	//protected $updateFields = array('usertype','typename','password','powercode','usergroup','groupname','email','unionid','uniontime','regip','dateline','mobile','birthday','about','gender','area','phone','qq','provid','cityid','distid','provname','cityname','distname','address','SecurityForm');
	
	
	//字段检查-----------------------------------------------------------------------------------------------
	protected $_validate = array(
		//array('title','require','请输入名称！'),
	);
	
	//数据过滤-----------------------------------------------------------------------------------------------
	function FormatData($array=array()){
		$data['fromuid']=$this->uid;
		$data['toname']=String::msubstr(I('post.username'),0,30,C('S_CHARSET'),false);
		$data['content']=String::msubstr(I('post.content'),0,30,C('S_CHARSET'),false);
		$data['dateline']=$data['lasttime']=NowTime();
		$data['SecurityForm']=I('post.SecurityForm','','string');
		
		return array_merge($data,$array);
	}
	
	function CheckDefaultData(){
		$data=$this->FormatData();
		$touid=intval($_POST['touid']);
		if(!$touid){
			if(!$data['toname']){
				$this->error='用户名不能为空！';
				return false;
			}
				
			if($this->username==$data['toname']){
				$this->error='不能发给自己！';
				return false;
			}
		}else{
			if($this->uid==$touid){
				$this->error='不能发给自己！';
				return false;
			}
		}
		
		if(!$data['content']){
			$this->error='内容不能为空！';
			return false;
		}

		
		$member=new \Member\Model\MemberModel();
		if(!$touid){
			$result=$member->UserNameGetMember($data['toname']);
		}else{
			$result=$member->UidGetMember($touid);
		}
		
		if($result['uid']>0 && $result['uid']!=$this->uid){
			return array('touid'=>$result['uid'],'toname'=>$result['username']);
		}elseif($result['uid']>0 && $result['uid']==$this->uid){
			$this->error='不能发给自己！';
		}else{
			$this->error='用户名不存在！';
		}
		
		return false;
	
	}
	
	
	function InsertDialogData($array=array()){
		
		$formatdata=$this->FormatData($array);
	
		//是否有过对话
		$dialogarray=$this->token(false)->where(" fromuid=$this->uid AND touid=$formatdata[touid] ")->find();
	
		$id=!empty($dialogarray['activity']) ? $dialogarray['activity'] : $this->InsertData($formatdata);
		
		if($id>0){
			
			//插入 member_dialog_message
			if (M('MemberDialogMessage')->token(false)->create(array('aid'=>$id,'fromuid'=>$this->uid,'fromname'=>$this->username,'touid'=>$formatdata['touid'],'content'=>$formatdata['content'],'dateline'=>$formatdata['dateline']))){
				M('MemberDialogMessage')->token(false)->add();
				$socketparams=array('event'=>'dialog','uid'=>$formatdata['touid'],'content'=>json_encode(array('id'=>$id,'uid'=>$this->uid,'username'=>$this->username,'touid'=>$formatdata['touid'],'avatar'=>GetAvatarSimple($this->uid,48,'socket_avatar'),'message'=>$formatdata['content'],'url'=>U('/member/dialog/show/id/'.$id))));
				tag('SocketIO',$socketparams);
			}
			
			$formatdata['fromname']=$this->username;
			$formatdata['lastmessage']=serialize($formatdata);
			$aid=intval($dialogarray['activity']);

			if(empty($aid)){
				$toread=$fromread=$fromcount=$tocount=1;
				$this->token(false)->where(" id=$id ")->data(array('activity'=>$id))->save();
			}else{
				//统计
				$fromcount=M('MemberDialogMessage')->token(false)->where(" aid=$id AND status!=$dialogarray[fromuid] ")->count();
				$tocount=M('MemberDialogMessage')->token(false)->where(" aid=$id AND status!=$dialogarray[touid] ")->count();
				
				//未阅读数
				$fromread=M('MemberDialogMessage')->token(false)->where(" aid=$id AND fromread=0 AND status!=$dialogarray[fromuid]")->count();
				$toread=M('MemberDialogMessage')->token(false)->where(" aid=$id AND toread=0 AND status!=$dialogarray[touid] ")->count();
			}
			
			
			if(empty($aid) || $this->token(false)->where(" activity=$aid ")->count()==1){
				//新增 member_dialog
				if ($this->token(false)->create(array('fromuid'=>$formatdata['touid'],'touid'=>$this->uid,'toname'=>$this->username,'activity'=>$id,'isread'=>$fromread,'iscount'=>$fromcount,'lastmessage'=>$formatdata['lastmessage'],'lasttime'=>$formatdata['lasttime'],'dateline'=>$formatdata['dateline']))){
					$this->token(false)->add();
				}
			}

			//更新 from
			if ($this->token(false)->create(array('activity'=>$id,'isread'=>$fromread,'iscount'=>$fromcount,'lastmessage'=>$formatdata['lastmessage'],'lasttime'=>$formatdata['lasttime']))){
				$this->token(false)->where(" fromuid=$this->uid AND activity=$id ")->save();
			}
			
			//更新 to
			if ($this->token(false)->create(array('activity'=>$id,'isread'=>$toread,'iscount'=>$tocount,'lastmessage'=>$formatdata['lastmessage'],'lasttime'=>$formatdata['lasttime']))){
				$this->token(false)->where(" touid=$this->uid AND activity=$id ")->save();
			}
			
			$this->UpdateMemberDialogCount($this->uid,intval($formatdata['touid']));
			
			return $id;
			
		}
		
		$this->error='提交数据失败！';
		return false;
	}
	
	function ListData(){
		//数据-------------------------------
		$pagenum=I('get.p',0,'int');
		$list=$this->where(" fromuid=$this->uid ")->order(' lasttime DESC ')->page($pagenum,10)->select();
		
		//页码-------------------------------
		$count=$this->where(" fromuid=$this->uid ")->count();
		$Page = new \Think\Page($count,10);

		return array('list'=>$list,'page'=>$Page->show(),'pagenum'=>$pagenum);
	}
	
	function GetUserIm(){
		$list=$this->where(" fromuid=$this->uid ")->order(' lasttime DESC ')->field('id,fromuid,touid,toname,isread,activity,iscount')->limit(30)->select();
		if(!empty($list)){
			for($i=0;$i<count($list);$i++){
				$list[$i]['avatar']=GetAvatarSimple($list[$i]['touid'],48,'foxphp_user_avatar image-circular');
			}
		}
		return array('list'=>$list);
	}
	
	function ShowData(){
		$id=intval($_GET['id']);
		//数据-------------------------------
		$pagenum=I('get.p',0,'int');
		$list=M('MemberDialogMessage')->where(" aid=$id AND status!=$this->uid ")->order(' dateline DESC ')->page($pagenum,10)->select();
		
		//页码-------------------------------
		$count=M('MemberDialogMessage')->where(" aid=$id AND status!=$this->uid ")->count();
		$Page = new \Think\Page($count,10);

		return array('list'=>$list,'page'=>$Page->show(),'pagenum'=>$pagenum);
	}
	
	function GetOneData(){
		$id=intval($_GET['id']);
		return $this->token(false)->where(" fromuid=$this->uid AND activity=$id ")->find();
	}
	
	
	function UpdateDialogRead($list=array(),$id=0){
		if(!$id){
			$id=intval($_GET['id']);
		}
		if($list['list']){
			$ids='';
			foreach($list['list'] as $value){
				$ids.=empty($ids) ? intval($value['id']) : ','.intval($value['id']);
			}

			if($ids){
				M('MemberDialogMessage')->token(false)->where(" id IN($ids) AND fromuid=$this->uid ")->data(array('fromread'=>1))->save();
				M('MemberDialogMessage')->token(false)->where(" id IN($ids) AND touid=$this->uid ")->data(array('toread'=>1))->save();
				
				$fromread=M('MemberDialogMessage')->token(false)->where(" aid=$id AND fromuid=$this->uid AND fromread=0 AND status!=$this->uid ")->count();
				$toread=M('MemberDialogMessage')->token(false)->where(" aid=$id AND touid=$this->uid AND toread=0 AND status!=$this->uid ")->count();
				$this->token(false)->where(" fromuid=$this->uid AND activity=$id ")->data(array('isread'=>$fromread+$toread))->save();
			}
			
			foreach($list['list'] as $value){
				$this->UpdateMemberDialogCount(intval($value['fromuid']),intval($value['touid']));
			}
		}
	}
	
	//Member表 Dialog 字段
	function UpdateMemberDialogCount($fromuid=0,$touid=0){
		if($fromuid>0){
			$isread=intval($this->token(false)->where(" fromuid=$fromuid ")->sum('isread'));
			M('Member')->token(false)->where(" uid=$fromuid ")->data(array('dialogread'=>$isread))->save();
		}
		
		if($touid>0){
			$isread=intval($this->token(false)->where(" fromuid=$touid ")->sum('isread'));
			M('Member')->token(false)->where(" uid=$touid ")->data(array('dialogread'=>$isread))->save();
		}
	}
	
	function DeleteDialogData($ids=null){
		if(!$ids){
			$ids=explode(',',$_POST['id']);
		}
		
		if($ids){
			foreach($ids as $value){
				$id=intval($value);
				if($id){
					//对方是否已删除
					$dialog=$this->token(false)->where(" id=$id ")->find();
					$aid=intval($dialog['activity']);
					$count=$this->token(false)->where(" activity=$aid ")->count();
					if($aid>0 && $count==2){
						$this->token(false)->where(" id=$id ")->delete();
						//删除
						M('MemberDialogMessage')->token(false)->where(" aid=$aid AND status>0 AND status!=$this->uid ")->delete();
						
						//隐藏
						M('MemberDialogMessage')->token(false)->where(" aid=$aid AND status=0 ")->data(array('status'=>$this->uid))->save();
					}elseif($aid>0 && $count==1){
						//删除全部
						M('MemberDialogMessage')->token(false)->where(" aid=$aid ")->delete();
						$this->token(false)->where(" activity=$aid ")->delete();
					}
					
					if($aid>0 && $dialog['fromuid'] && $dialog['touid']){
						$this->UpdateMemberDialogCount($dialog['fromuid'],$dialog['touid']);
					}

				}
			}
			
		}
	}
}

?>